#-*-coding:utf-8-*-
'''
file.py : contains utilities and wrapper in i/o manipulation about files
'''
import os
from types import *

def is_file(path):
    '''
    checks the existence of file :

    '''

def is_readable_file(path):
    '''
    check whether the given path refers to a readable ressource
    param : path, the path of the ressource to be checked
    returns : true is the path is readable
    '''
    return os.access(path, os.R_OK)

def is_opened_file(object):
    '''
    checks if the object object is a opened file produced with the builtin open function
    '''
    return (type(object) is FileType)

def get_file_handle(path, mode='r'):
    if is_readable_file(path):
        return open(path,mode)

def read_file_array(path,mode='r',opts=''):
    '''
    reads sequentially a file, assuming that a text file
    param : path, the path of the file
    param : mode, the mode passed to open function
    returns : an list filled with the file content : 1 line / 1 entry, False otherwise
    '''
    if is_readable_file(path):
        res = []
        with open(path,mode) as fp:
            for line in fp:
                res.append(line)
            fp.close()
        return res
    else :
        return False
    
def read_file(path,mode='r'):
    '''
    reads a file entirely
    param : path, the path of the file
    param : mode, the mode passed to open function
    returns : string filled with the entire content of the file, False otherwise
    '''
    if is_readable_file(path):
        f =  open(path,mode) # file 
        c = f.read() # content
        f.close() # free all ressources 
        return c # returns file contents
        
    else :
        return False
    
def append(file,content='',closeAfter=True):
    '''
    Append content to file file where file is a path or an opened file ( produced by open function)
    params : file, file-object or path to the file to modify
    params : content, the content to be added to the file
    params : closeAfter, a boolean, closes the ressources after using it or not
    '''
    if content :
        if is_opened_file(file): # if file is a file-object
            try :
                file.write(content) # appends the content to file
                if closeAfter: 
                    file.close()
                return True # All goes good !
            except :
                return False # if an exception occurs during the process
        else:
            if is_readable_file(file):
                f = get_file_handle(file,'a') # open the file
                return append(f,content,closeAfter) # append content with the same function
            else :
                return False # if the path given is not readable
    else :
        return False # if no content to add
        
